package com.qst.mapreduce.wordcount.shiyanwu.mysql;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class MysqlMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        String line = value.toString();
        String[] wordList = line.split("\t");
        String province = wordList[0];
        int total = Integer.parseInt(wordList[1]);
        saveProvince(province,total);
    }

    public void saveProvince(String province,int total){
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            //获取数据库连接对象
            Connection conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/my-web","root","123456");
            //定义sql语句
            String sql="insert into province(province,total) values ('"+province+"',"+total+")";
            //获取执行sql的对象
            Statement stmt=conn.createStatement();
            //执行sql
            stmt.execute(sql);
            stmt.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void setup(Mapper<LongWritable, Text, Text, IntWritable>.Context context) throws IOException, InterruptedException {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            //获取数据库连接对象
            Connection conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/my-web","root","1234");
            //获取执行sql的对象
            Statement stmt=conn.createStatement();
            //执行sql
            stmt.execute("TRUNCATE province");
            stmt.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}